package com.chb.pagerank;
import java.io.IOException;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
public class Node {
	//每个页面的出事pr值为1.0
	private double pageRank=1.0;
	//该节点的出链指向的节点
	private String[] adjacentNodeNames;
	//各个节点的分隔符
	public static final char fieldSeparator = '\t';

	public double getPageRank() {
		return pageRank;
	}

	public Node setPageRank(double pageRank) {
		this.pageRank = pageRank;
		return this;
	}

	public String[] getAdjacentNodeNames() {
		return adjacentNodeNames;
	}

	public Node setAdjacentNodeNames(String[] adjacentNodeNames) {
		this.adjacentNodeNames = adjacentNodeNames;
		return this;
	}
	//判断是否有出链节点
	public boolean containsAdjacentNodes() {
		return adjacentNodeNames != null && adjacentNodeNames.length>0;
	}

	@Override
	public String toString() {//每个节点打印信息:PageRank值		 出链节点1		出链节点2	...
		StringBuilder sb = new StringBuilder();
		sb.append(pageRank);
		if (getAdjacentNodeNames() != null) {
			sb.append(fieldSeparator)
			.append(StringUtils
					.join(getAdjacentNodeNames(), fieldSeparator));
		}
		return sb.toString();
	}

	/**
	 * @param value  给定一个字符串  value =1.0	B	D 
	 * @return      将这个字符串1封装成Node对象。
	 */
	public static Node fromMR(String value) throws IOException {
		String[] parts = StringUtils.splitPreserveAllTokens(
				value, fieldSeparator);
		if (parts.length < 1) {
			throw new IOException(
					"Expected 1 or more parts but received " + parts.length);
		}
		Node node = new Node()
		.setPageRank(Double.valueOf(parts[0]));
		if (parts.length > 1) {
			node.setAdjacentNodeNames(Arrays.copyOfRange(parts, 1,
					parts.length));
		}
		return node;
	}
}
